package book.hadoop.ch04;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.util.ReflectionUtils;
/**
 * 参数：hdfs://hadoop.main:9000/sequence-file-test
 * @author conkeyn
 *
 */
public class MapFIleReaderDemo {

	public static void main(String[] args) throws IOException, URISyntaxException {
		String uri = args[0];
		Configuration config = new Configuration();
		FileSystem fs = FileSystem.get(new URI(uri), config);
		Path path = new Path(uri);
		MapFile.Reader reader = null;
		try {
			reader = new MapFile.Reader(fs, uri, config);
			WritableComparable key = (WritableComparable) ReflectionUtils.newInstance(reader.getKeyClass(), config);
			Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), config);
			while (reader.next(key, value)) {//当next()方法返回false时表示到达文件末尾
				
				System.out.printf("[%s]\t%s\n", key.toString(), value.toString());
			}
			System.out.println("===============");
			Text val =new Text();//val对象不能置空，需要new
			System.out.println(reader.get(new IntWritable(496), val));//根据key读取值
			System.out.println(val);
			//取得与键值496相近的键值，当取不到496时，就取出相近的键值，而get()方法是返回NULL。
			System.out.println(reader.getClosest(new IntWritable(496), val));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeStream(reader);
		}
	}

}
